const bouncer = require('koa-bouncer');
const ErrorCode = require('@/lib/error/code');
const { debug } = require('../../config/index');
const WLog4 = require('@/lib/log4/index');
const WLogALi = require ('@/lib/aliyun/logs')

/**
 * 错误处理
 * @param ctx 环境上下文
 * @param next 下一步
 * @returns {Promise<void>}
 */
const logger = async (ctx, next) => {
	// 错误处理
	try {
		await next();
	} catch(err) {
		try {

			const status = err.code ? 200 : err.statusCode || err.status || 500

			// ===================== 错误情况下日志打印 ==================
			if (status === 304) {
				ctx.status = status
				ctx.response.body = '304 -catch'
				return
			}

			// ===================== 调试模式下控制台打印 ==================
			if (debug) {
				console.log('============== 错误 ===============')
				console.log(err)
			}

			// ===================== log4 ==================
			const errCode = err.code ? `${err.code}` : ''
			const errorMsg = `${status} ${ errCode } ${err.message || err.msg}`
			WLog4.error(errorMsg)

			// ===================== koa-bouncer错误 ==================
			if (err instanceof bouncer.ValidationError) {
				ctx.status = 200
				ctx.response.body = {
					code: ErrorCode.parameterErr.code,
					msg: err.bouncer.message
				}
			}
			// ===================== MongooseError错误 ==================
			else if (err.constructor.name === 'MongooseError') {
				ctx.status = 200
				ctx.response.body = {
					code: ErrorCode.mongoErr.code,
					msg: err
				}
			}
			// ===================== 未知错误 ==================
			else {
				ctx.status = status
				ctx.response.body = {
					code: err.code,
					msg: err.msg || err.message
				}
			}
		} catch (e) {
			let msg = null
			if (typeof e === 'string') {
				msg = e
			} else if (typeof e === 'object') {
				msg = e.message
			}
			ctx.response.body = {
				code: ErrorCode.unknownErr.code,
				msg: msg || ErrorCode.unknownErr.msg
			}
		}
	}
}

module.exports = logger
